<template>
  <TodoAdd @addTodo="AddArray"></TodoAdd>
  <TodoUl>
    <TodoList v-for="todo in Array" :key="todo.id" v-bind="todo" @cut="Appcut" @edit="Appedit" @EachDelete="Appdel">
    </TodoList>
  </TodoUl>
  <TodoDelete :Array="Array" @selectAll="Appselect" @clearpart="Appclepart" @clearAll="Appcleall">
  </TodoDelete>
</template>
<script setup>
import TodoAdd from './components/TodoAdd.vue';
import TodoUl from './components/TodoUl.vue';
import TodoList from './components/TodoList.vue';
import TodoDelete from './components/TodoDelete.vue';

import { ref, onMounted, watch } from 'vue'

const Array = ref([])
const AddArray = (todo) => {
  Array.value.push(todo)
}

const Appcut = (id, checked) => {
  const index = Array.value.findIndex((todo) => todo.id === id)
  Array.value[index].done = checked
}

const Appedit = (id, content) => {
  const index = Array.value.findIndex((todo) => todo.id === id)
  Array.value[index].content = content
}

const Appdel = (id) => {
  const index = Array.value.findIndex((todo) => todo.id === id)
  Array.value.splice(index, 1)
}

const Appselect = (checked) => {
  todos.value.forEach((todo) => (todo.done = checked))
}

const Appclepart = () => {
  Array.value = Array.value.filter((todo) => !todo.done)
}
const Appcleall = () => {
  Array.value = []
}

const getTodos = () => {
  const todoLists = JSON.parse(localStorage.getItem('todoLists') || '[]')
  Array.value = todoLists
}
watch(
  Array,
  () => {
    localStorage.setItem('todoLists', JSON.stringify(Array.value))
  },
  { deep: true }
)

onMounted(() => {
  getTodos()
})
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
</style>